/**
 * Javascript source file for galaxygalaxyview.php
 */

var GalaxytoolMoonCalcMouseOver = false;

function load_system() {
	var galaxy = parseInt(dojo.byId("galaxy").value);
	if (galaxy < 1) galaxy = 1;
	var system = parseInt(dojo.byId("system").value);
	if (system < 1) system = 1;
	
	if (dijit.byId("galaxy").get("state") != "" || dijit.byId("system").get("state") != "") return;
	
	window.location.hash = "#select_" + (galaxy*1000 + system);
	// show loading icon at galaxyview
	dojo.byId("loading_icon").style.display = "";
	dojo.style(dijit.byId('go').domNode, {
		  visibility: ('hidden'),
		  display: ('none')
		});
	
	var xhrArgs = {
	        url: "ajax/ajax_galaxyview.php?galaxy="+galaxy+"&system="+system,
	        handleAs: "json",
	        load: function(jsonData) {
	        	show_new_system_data(jsonData);
	        	dojo.style(dijit.byId('go').domNode, {
	      		  visibility: ('visible'),
	      		  display: ('block')
	      		});
	        	
	        	dojo.byId("loading_icon").style.display = "none";

	        	//dijit.byId("underlay").hide();
	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);
	dojo.byId("messageArea").style.display    = "none";
}

function show_new_system_data(jsonData) {
	
	for(var i=1; i<=15; i++) {
		initialize_data(i);
	}

	var galaxy = parseInt(dojo.byId("galaxy").value);
	if (galaxy < 1) galaxy = 1;
	var system = parseInt(dojo.byId("system").value);
	if (system < 1) system = 1;
	
	if (jsonData.last_update != "") {
		var content = ' <div class="system_updated">'+jsonData.username+' @ '+jsonData.last_update+'</div>';
	} else {
		var content = TEXT_VIEW_NODATA;
	}
	dojo.byId("galaxy_info").innerHTML = content;
	
	for(var i=0; i<jsonData.planets.length; i++) {
		fill_position(jsonData.planets[i]);
	}
	
	// colonies
	dojo.byId("colonies").innerHTML = jsonData.planets.length;
	
	// phalanx ranges
	if (jsonData.phalanx.length == 0) {
		dojo.byId("phalanx").innerHTML = TEXT_VIEW_NOMOONS;
	} else {
		var content = "";
		for(var i=0; i<jsonData.phalanx.length; i++) {
			var coordinates = jsonData.phalanx[i].g+":"+jsonData.phalanx[i].s+":"+jsonData.phalanx[i].p;
			content += '<span class="hyperlink '+jsonData.phalanx[i].d+'" style="margin-left:10px;" onClick="show_report(\''+coordinates+'\',true)">'+coordinates+'</span> ';
		}
		dojo.byId("phalanx").innerHTML = '<div style="max-width: 640px;">'+content+'</div>';
	}
	
	// irak ranges
	if (jsonData.irak.length == 0) {
		dojo.byId("irak").innerHTML = TEXT_VIEW_NOIRAKS;
	} else {
		var content = "";
		for(var i=0; i<jsonData.irak.length; i++) {
			var coordinates = jsonData.irak[i].g+":"+jsonData.irak[i].s+":"+jsonData.irak[i].p;
			content += '<span class="hyperlink '+jsonData.irak[i].d+'" style="margin-left:10px;" onClick="show_report(\''+coordinates+'\',false)">'+coordinates+'</span> ';
		}
		dojo.byId("irak").innerHTML = '<div style="max-width: 640px;">'+content+'</div>';
	}
}

function fill_position(jsonData) {
	var position = jsonData.pos;
	
	// Planetposition
	var css_class = (jsonData.diplomatic_status != "nothing") ? "bg_"+jsonData.diplomatic_status+" galaxyview_diplomatic_status_overlay centered_text" : "centered_text";
	dojo.byId("planetpos_"+position).className = css_class;
	
	// Planet icon
	dojo.byId("planeticon_"+position).setAttribute("class", "planet");
	
	// Planetname
	if (jsonData.fleetmoves == true) {
		var fleet_move_icon = '<img class="hyperlink" src="../images/spaceship_right.png" onclick="ShowFleetMove('+jsonData.galaxy+','+jsonData.system+','+position+')" height="16" width="16" alt="fleet movement" style="vertical-align:bottom" />';
		dojo.byId("planetname_"+position).innerHTML = jsonData.planetname + " " + fleet_move_icon;
	} else {
		dojo.byId("planetname_"+position).innerHTML = jsonData.planetname;		
	}
	
	// Moon
	if (jsonData.moonsize > 0) {
		dojo.byId("moon_"+position).innerHTML = 
			'<span id="moon_calc_'+position+'" style="cursor: pointer;" onMouseOver="showMoonCalc(\''+position+'\');"><img height="30" width="30" src="../images/OGame/moon.gif"></span>'+
			'<input id="moonsize_'+position+'" type="hidden" value="'+jsonData.moonsize+'">';
	}
	// Debris
	jsonData.metal = parseInt(jsonData.metal);
	jsonData.crystal = parseInt(jsonData.crystal);
	if (jsonData.metal > 0 || jsonData.crystal > 0) {
		var metal_display = (jsonData.metal > 0) ? "block" : "none";  
		var crystal_display = (jsonData.crystal > 0) ? "block" : "none";  
		
		dojo.byId("debris_"+position).innerHTML = '<img height="30" width="30" src="../images/OGame/tf_a.gif">';
		var mouse_over = '<div style=font-size:10pt;>'+
			'<div>'+TEXT_SHOW_METAL_LONG+': '+NumberFormat(jsonData.metal)+'</div>'+
			'<div>'+TEXT_SHOW_CRYSTAL_LONG+': '+NumberFormat(jsonData.crystal)+'</div><br>'+
			TEXT_REPORTS_FOR_TF+':<br>'+TEXT_REPORTS_REC+': <span id="recycler_'+position+'">'+
			NumberFormat(Math.ceil((jsonData.metal + jsonData.crystal) / 20000))+'</span></div>';	

		new dijit.Tooltip({
			 id: "debristooltip_"+position,
		     connectId: ["debris_"+position],
		     //position: "above", -- dojo bug: http://bugs.dojotoolkit.org/ticket/14833
		     label: mouse_over
		  });
	}
	// Player
	if (jsonData.playername != null) {
	var player_status_text     = (jsonData.rank > 0) ? TEXT_STATS_PLAYERSTATS : TEXT_SHOW_NOTRANKED;
	if (jsonData.banned == "true") {
		jsonData.rank = 0;
		jsonData.erank = 0;
		jsonData.frank = 0;
		jsonData.rrank = 0;
		jsonData.hrank = 0;
		jsonData.mbrank = 0;
		jsonData.mdrank = 0;
		jsonData.mlrank = 0;
	}
	var player_status = get_player_status_string(jsonData.banned,jsonData.vacation,jsonData.noob,jsonData.inactive,jsonData.long_inactive,jsonData.outlaw); // general.js
	if (player_status != "") player_status = "("+player_status+")";
	
	dojo.byId("player_"+position).innerHTML = 
		'<a id="player_anchor_'+position+'" href="playerinformation.php?id='+escape(jsonData.player_id)+'">'+jsonData.playername+'</a><span style="padding-left: 5px;">'+player_status+'</span>';
	
	var mouse_over = '<div class="'+jsonData.diplomatic_status+'" style="font-size:10pt;">'+player_status_text+"</div>";
	if (jsonData.rank > 0) {
		mouse_over += 
		'<div>'+
			'<table>'+
			'<tr><td>'+TEXT_SHOW_RANK+":</td><td>#"+jsonData.rank+"</td>"+
			'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.points)+"</td>"+
			'</tr>'+
			'<tr>'+
				'<td>'+TEXT_STATS_ECONOMY+":</td><td>#"+jsonData.erank+"</td>"+
				'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.epoints)+"</td>"+
			'</tr>'+
			'<tr><td>'+TEXT_STATS_MILITARY+":</td><td>#"+jsonData.frank+"</td>"+
			'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.fpoints)+"</td>"+
			'</tr>'+
			'<tr><td>'+TEXT_STATS_RESEARCH+":</td><td>#"+jsonData.rrank+"</td>"+
			'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.rpoints)+"</td>"+
			'</tr>'+
			'<tr><td>'+TEXT_STATS_HONOUR+":</td><td>#"+jsonData.hrank+"</td>"+
			'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.hpoints)+"</td>"+
			'</tr>'+
			'<tr><td>'+TEXT_STATS_MILITARY_BUILD+":</td><td>#"+jsonData.fbrank+"</td>"+
			'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.fbpoints)+"</td>"+
			'</tr>'+
			'<tr><td>'+TEXT_STATS_MILITARY_DESTROYED+":</td><td>#"+jsonData.fdrank+"</td>"+
			'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.fdpoints)+"</td>"+
			'</tr>'+
			'<tr><td>'+TEXT_STATS_MILITARY_LOST+":</td><td>#"+jsonData.flrank+"</td>"+
			'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.flpoints)+"</td>"+
			'</tr>'+
			'</table><br>'+
			TEXT_STATS_UPDATE+": "+jsonData.plastupdate+
		'</div>';
	}
	
	new dijit.Tooltip({
		 id: "playertooltip_"+position,
	     connectId: ["player_anchor_"+position],
	     //position: "above", -- dojo bug: http://bugs.dojotoolkit.org/ticket/14833
	     label:  mouse_over
	  });
	} // else:  no player - only debris
	
	// Ally
	if (jsonData.allyname != null) {
		var ally_class = (jsonData.dipl_status != "nothing") ? 'class="'+jsonData.dipl_status+'"' : "";
		
		var content = 
			'<a id="ally_anchor_'+position+'" href="allyinformation.php?id='+escape(jsonData.alliance_id)+'"><span '+ally_class+'>'+jsonData.allyname+'</span></a>';
		dojo.byId("ally_"+position).innerHTML = content;
		
		var ally_status_text     = (jsonData.arank > 0) ? TEXT_STATS_ALLYSTATS : TEXT_SHOW_NOTRANKED;
		
		var mouse_over = '<div class="'+jsonData.dipl_status+'" style= "font-size:10pt;">'+ally_status_text+'</div>';
		if (jsonData.rank > 0) {
			mouse_over +=
				'<div>'+
				'<table>'+
				'<tr><td>'+TEXT_STATS_MEMBERS+':</td><td colspan="3">'+jsonData.members+'</td>'+
				'</tr>'+
				'<tr><td>'+TEXT_SHOW_RANK+':</td><td>#'+jsonData.arank+'</td>'+
				'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.apoints)+"</td>"+
				'<tr>'+
					'<td>'+TEXT_STATS_ECONOMY+":</td><td>#"+jsonData.aerank+"</td>"+
					'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.aepoints)+"</td>"+
				'</tr>'+
				'<tr><td>'+TEXT_STATS_MILITARY+":</td><td>#"+jsonData.afrank+"</td>"+
				'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.afpoints)+"</td>"+
				'</tr>'+
				'<tr><td>'+TEXT_STATS_RESEARCH+":</td><td>#"+jsonData.arrank+"</td>"+
				'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.arpoints)+"</td>"+
				'</tr>'+
				'<tr><td>'+TEXT_STATS_HONOUR+":</td><td>#"+jsonData.ahrank+"</td>"+
				'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.ahpoints)+"</td>"+
				'</tr>'+
				'<tr><td>'+TEXT_STATS_MILITARY_BUILD+":</td><td>#"+jsonData.afbrank+"</td>"+
				'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.afbpoints)+"</td>"+
				'</tr>'+
				'<tr><td>'+TEXT_STATS_MILITARY_DESTROYED+":</td><td>#"+jsonData.afdrank+"</td>"+
				'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.afdpoints)+"</td>"+
				'</tr>'+
				'<tr><td>'+TEXT_STATS_MILITARY_LOST+":</td><td>#"+jsonData.aflrank+"</td>"+
				'<td style="padding-left: 5px;">'+TEXT_STATS_SCORE+":</td><td>"+NumberFormat(jsonData.aflpoints)+"</td>"+
				'</tr>'+				
				'</table><br>'+
				TEXT_STATS_UPDATE+": "+jsonData.alastupdate+
			'</div>';	
		}
		
		new dijit.Tooltip({
			 id: "allytooltip_"+position,
		     connectId: ["ally_anchor_"+position],
		     //position: "above", -- dojo bug: http://bugs.dojotoolkit.org/ticket/14833
		     label: mouse_over
		  });	
	}

	
	// Notices
	if (jsonData.notice_id != null) {
		var content = '<img class="hyperlink" onClick="ShowNoticeContent('+jsonData.player_id+')" src="../images/notice.gif" width="15" height="17" alt="notice" border="0">';
	} else {
		var content = '<img class="hyperlink" onClick="CreateNoticeContent('+jsonData.player_id+')" src="../images/no_notice.gif" width="15" height="17" alt="notice" border="0">';
	}
	dojo.byId("notice_"+position).innerHTML = content;
	
	// Reports
	var coordinates = jsonData.galaxy + ":" + jsonData.system + ":" + position;
	if (jsonData.planet_report == true) {
		var content1 = '<a href="report.php?coordinates='+coordinates+'&amp;moon=false" onClick="show_report(\''+coordinates+'\',false); return false;"'+
						' onmouseover="show_report(\''+coordinates+'\',false,undefined,true); galaxytool.report_display.ReportTooltipMouseOver();"'+
						' onmouseout="galaxytool.report_display.ReportTooltipMouseLeave(); setTimeout(galaxytool.report_display.CloseReportTooltipIfNotUsed, 750)">'+
						'<img src="../images/spio.gif" width="15" height="17" alt="combat report" border="0"></a>';
	} else {
		var content1 = '';
	}
	if (jsonData.moon_report == true) {
		var content2 = '<a href="report.php?coordinates='+coordinates+'&amp;moon=true" onClick="show_report(\''+coordinates+'\',true); return false;"'+
						' onmouseover="show_report(\''+coordinates+'\',true,undefined,true); galaxytool.report_display.ReportTooltipMouseOver();"'+
						' onmouseout="galaxytool.report_display.ReportTooltipMouseLeave(); setTimeout(galaxytool.report_display.CloseReportTooltipIfNotUsed, 750)">'+
						'<img src="../images/spio.gif" width="15" height="17" alt="combat report" border="0"></a>';
	} else {
		var content2 = '';
	}
	dojo.byId("reports1_"+position).innerHTML = content1;
	dojo.byId("reports2_"+position).innerHTML = content2;
	
}


function initialize_data(position) {
	
	dojo.byId("planetpos_"+position).className = "centered_text"; // remove diplomatic status
	
	var control = dijit.byId("playertooltip_"+position);
	if (control) {
	     /* it exists! */
		control.destroy();
		control = null;
	} 
	var control = dijit.byId("allytooltip_"+position);
	if (control) {
		control.destroy();
		control = null;
	} 
	var control = dijit.byId("debristooltip_"+position);
	if (control) {
		control.destroy();
		control = null;
	}
	
	dojo.byId("planeticon_"+position).setAttribute("class", "no_planet");
	
	var convert_blank = new Array("planetname_","moon_","debris_","player_","ally_","notice_","reports1_","reports2_");
	for (var i = 0; i < convert_blank.length; i++) {
		dojo.empty( convert_blank[i].toString() + position.toString() );
	}
	
}

function galadown () {
	var galaxy = parseInt(dojo.byId("galaxy").value) - 1;
	if (galaxy < 1) galaxy = 1;
	dojo.byId("galaxy").value = galaxy;
	dijit.byId("galaxy").validate();
	load_system();
}
function galaup () {
	dojo.byId("galaxy").value = parseInt(dojo.byId("galaxy").value) + 1;
	dijit.byId("galaxy").validate();
	load_system();
}
function systemdown () {
	var system = parseInt(dojo.byId("system").value) - 1;
	if (system < 1) system = 1;
	dojo.byId("system").value = system;
	dijit.byId("system").validate();
	load_system();
}
function systemup () {
	dojo.byId("system").value = parseInt(dojo.byId("system").value) + 1;
	dijit.byId("system").validate();
	load_system();
}

function cursorevent(event) {
	if(event.keyCode == 37) {
		systemdown();
	}
	if(event.keyCode == 39) {
		systemup();
	}
	if(event.keyCode == 38) {
		galaup();
	}
	if(event.keyCode == 40) {
		galadown();
	}
	if(event.keyCode == 13) { // enter
		load_system();
	}
}

function ShowFleetMove(galaxy, system, planet) {
	dojo.byId("messageArea").style.display    = "none";
	dijit.byId("FleetDialogContent").set("href",'ajax/ajax_fleetmove_all.php?galaxy='+galaxy+"&system="+system+"&planet="+planet);
	dijit.byId("FleetDialog").show();
}

function ShowNoticeContent(player_id) {
	dojo.byId("messageArea").style.display    = "none";
	dijit.byId("NoticeDialogContent").set("href",'ajax/ajax_notices_read.php?playerid='+player_id);
	dojo.byId("NoticeDialogEdit").setAttribute("onclick", "EditNoticeContent("+player_id+")");
	dojo.byId("NoticeDialogEdit").style.display="";
	dijit.byId("NoticeDialog").show();
}
function EditNoticeContent(player_id) {
	dijit.byId("NoticeDialogContent").set("href",'ajax/ajax_notices_edit.php?playerid='+player_id+"&dialog=NoticeDialog&refresh=");
	dojo.byId("NoticeDialogEdit").style.display="none";
}
function CreateNoticeContent(player_id) {
	dojo.byId("messageArea").style.display    = "none";
	dijit.byId("NoticeDialogContent").set("href",'ajax/ajax_notices_edit.php?playerid='+player_id+"&dialog=NoticeDialog&refresh=");
	dojo.byId("NoticeDialogEdit").style.display="none";
	dijit.byId("NoticeDialog").show();
}



function GetMoonDestructionChance(moonsize, death_stars) {
	var destroy_chance = (100 - Math.sqrt(moonsize)) * Math.sqrt(death_stars);
	destroy_chance = Math.round(destroy_chance * 100) / 100;	
	return destroy_chance;
}

function ChangeMoonDestChance() {
	var moonsize = parseInt(dojo.byId('moonsize').value);
	if (isNaN(moonsize) || moonsize < 1) return;
	var death_star = parseInt(dijit.byId("death_stars").get("value"));
	if (isNaN(death_star) || death_star < 1) return; 
	dojo.byId("moon_chance_n").innerHTML = GetMoonDestructionChance(moonsize, death_star);
}

function MoonCalcClose(e) {
	dijit.popup.close(dijit.byId("moontooltip"));
	GalaxytoolMoonCalcMouseOver = false;
}

function CloseMoonCalcIfNotUsed() {
	if (GalaxytoolMoonCalcMouseOver == false) {
		dijit.popup.close(dijit.byId("moontooltip"));
	}
}
function showMoonCalc(ThreadID) {
	dojo.byId("messageArea").style.display    = "none";
	var size = parseInt(dojo.byId("moonsize_"+ThreadID).value);
	if (isNaN(size) || size < 1) return;
	
	dojo.byId("moonsize").value = size;
	dojo.byId("moonsize_display").innerHTML = NumberFormat(size);
	dojo.byId("moon_chance_1").innerHTML = GetMoonDestructionChance(size, 1);
	dojo.byId("moon_ds_lost").innerHTML  = Math.round((Math.sqrt(size)/2),2);
	dojo.byId("moon_chance_n").innerHTML = GetMoonDestructionChance(size, dojo.byId("death_stars").value);
	dijit.popup.open({ popup: dijit.byId("moontooltip"), around: dojo.byId("moon_calc_" + ThreadID) });
	window.setTimeout(CloseMoonCalcIfNotUsed, 2000); // close popup if mouse is not using it within 2 seconds
}

function MoonCalculatorMouseOver(e) {
	GalaxytoolMoonCalcMouseOver = true;
}

function show_fleet_by_id(id) {
	window.location.pathname = window.location.pathname.substring(0,window.location.pathname.lastIndexOf("/"))+"/fleet_movements.php#id="+id;
}

function galaxyview_init() {
	dojo.connect(dijit.byId("moontooltip"), "onMouseLeave", MoonCalcClose );
	dojo.connect(dijit.byId("moontooltip"), "onMouseOver", MoonCalculatorMouseOver );
	
	dojo.connect(dijit.byId("reporttooltip"), "onMouseLeave", galaxytool.report_display.CloseReportTooltip );
	dojo.connect(dijit.byId("reporttooltip"), "onMouseOver", galaxytool.report_display.ReportTooltipMouseOver );

	// select user defined galaxy
	var selection = window.location.hash;
	if (selection != "") {
		selection = selection.replace(/#select_/, "");
		try {
			selection = parseInt(selection);
			if (selection > 1001) {
				var galaxy = Math.floor(selection / 1000);
				var system = (selection - galaxy * 1000);
				
				if (parseInt(dijit.byId("galaxy").get('value')) != galaxy || parseInt(dijit.byId("system").get('value')) != system) {
					dijit.byId("galaxy").set('value',galaxy);
					dijit.byId("system").set('value',system);
					load_system();
				}
			} 
		} catch (ignore) { }
	}	
}
dojo.ready(galaxyview_init);

on_notice_save_functions['change_icon'] = function (dijitContentPane, playerid) { 
	try {
		for (var i=1; i<=15; i++) {
			var notice = dojo.byId("notice_"+i).innerHTML;
			if (notice.indexOf("NoticeContent("+playerid+")") > 0) {
				// we found notice icon for that player
				dojo.byId("notice_"+i).innerHTML = '<img class="hyperlink" onClick="ShowNoticeContent('+playerid+')" src="../images/notice.gif" alt="notice" border="0">';
			}
		}
	} catch(e) {
		console.log(e);
	}
};
on_notice_save_function_names.push('change_icon');
